C语言中回调函数的含义与使用场景详解

您所在的位置:网站首页 c语言 重定义 C语言中回调函数的含义与使用场景详解

C语言中回调函数的含义与使用场景详解

#C语言中回调函数的含义与使用场景详解| 来源: 网络整理| 查看: 265

目录详解C语言中回调函数的含义与使用场景(2)使用场景一(重定义):使用场景二(扩展函数功能):使用场景三(分层):总结

详解C语言中回调函数的含义与使用场景(2)

引言:在上一篇文章中介绍了回调函数的概念与使用方法,本节将深入地介绍回调函数典型的使用场景。通过使用回调函数可以实现驱动和应用程序的分离解耦,让程序更加地灵活。也可以借助回调函数实现插入自定义代码、分层设计程序的思想。

使用场景一(重定义):

在统一的接口中,动态地改变一个函数的功能。该函数的功能可以是加载参数、或者执行运算。示例如下:

typedef int (*my_calculate_t)(int a, int b); static int cal_sum(int a, int b) { printf("now is sumrn"); return a + b; } static int cal_sub(int a, int b) { printf("now is subrn"); return a - b; } static int cal_mul(int a, int b) { printf("now is mulrn"); return a * b; } static my_calculate_t s_cal = cal_sum; static int test2_cal (int a, int b) { int result = 0; if(s_cal) { result = s_cal(a ,b); printf("result=%drn", result); } return result; } void app_main(void) { printf("init donern"); int m = 10, n = 1, ret; ret = test2_cal(m, n); }

上述代码通过 test2_cal() 实现计算接口的统一。只需改变函数指针 s_cal 的值,就可以让 test2_cal()执行不同的功能。我们可以拷贝上述程序分别对 s_cal赋值 cal_sum、cal_sub、cal_mul实现在不改动其他代码的情况下,让 test2_cal 执行不同的运算。这种通过改变函数指针 s_cal 的值,让函数 test2_cal() 执行不同功能的特性,可以称之为重定义了test2_cal()的功能。

上述程序运行结果:

init donenow is sumresult=11

使用场景二(扩展函数功能):

可以在程序中定义多个回调函数,若定义了就执行,否则就略过。实现在函数中扩展更多代码的目的(就像一个钩子函数一样)。示例如下:

typedef int (*my_calculate_t)(int a, int b); static int cal_sum(int a, int b) { printf("now is sumrn"); return a + b; } static int cal_sub(int a, int b) { printf("now is subrn"); return a - b; } static int cal_mul(int a, int b) { printf("now is mulrn"); return a * b; } static my_calculate_t s_c_array[5] = {cal_sum, cal_sub}; static int test1_cal(int a, int b) { volatile int result = 0; volatile size_t i = 0; for(i=0; i


【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3